package com.oig.common.handler;

import com.oig.common.exception.BadRequestException;
import com.oig.common.module.SysResponse;
import com.oig.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * order值越低越优先执行
 */
@RestControllerAdvice
@Slf4j
@Order(value = 0)
public class RestExceptionHandler {

	@ExceptionHandler(ServiceException.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public SysResponse<String> serviceExceptionHandler(ServiceException e) {
		log.error("controller advice ServiceException:", e);
        return SysResponse.failed(e.getMessage());
    }

	@ExceptionHandler(BadRequestException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public SysResponse<String> badRequestExceptionHandler(BadRequestException e) {
		log.error("controller advice BadRequestException:", e);
		return SysResponse.failed(e.getMessage());
	}

	@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public SysResponse<String> validatorExceptionHandler(Exception exception) {
		log.error("controller advice valid exception:", exception);
		BindingResult bindResult ;
		if (exception instanceof MethodArgumentNotValidException) {
			bindResult = ((MethodArgumentNotValidException) exception).getBindingResult();
		} else {
			bindResult = ((BindException) exception).getBindingResult();
		}
		StringBuilder stringBuilder = new StringBuilder();
		List<FieldError> fieldErrors=bindResult.getFieldErrors();
        for (int i=0;i<fieldErrors.size() ;i++){
			FieldError error = fieldErrors.get(i);
			if (i==0){
				stringBuilder.append(error.getDefaultMessage());
			} else {
				stringBuilder.append(";").append(error.getDefaultMessage());
			}
            log.error(error.getField()+":"+error.getDefaultMessage());
        }
		return SysResponse.failed(stringBuilder.toString());
    }


	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public SysResponse<String> ExceptionHandler(Exception e) {
		log.error("controller advice exception:", e);
		return SysResponse.failed("请检查输入数据或联系系统管理员");
	}


}
